<?php

/**
 *
 * Copyright (c) 2011 Tomáš Holub (tomas.holub@webadvice.cz)
 * 
 * @author Tomáš Holub (tomas.holub@webadvice.cz)
 * @package OverFishCMS
 */

namespace OverFish\Security;

use Nette;
use Nette\Security as NS;

class Authenticator extends Nette\Object implements NS\IAuthenticator {
    
    public $connection;

    function __construct(\DibiConnection $connection)
    {
        $this->connection = $connection;
    }

    function authenticate(array $credentials)
    {
        list($username, $password) = $credentials;
        $row = $this->connection->select('*')
                        ->from('user')
                        ->where('username = %i', $username)->fetch();

        if (!$row) {
            throw new NS\AuthenticationException('User not found.');
        }

        if ($row->password !== md5($password)) {
            throw new NS\AuthenticationException('Invalid password.');
        }
        
        $this->connection->update("user", array("last_login" => new \DateTime()))
                ->where('username = %i', $username)->execute();

        return new Identity($row->id, $username, array(), array("fullname" => $row->fullname));
    }
}

?>
